<?php
class Model_WebServices extends Model
{

	/*jTable function(EQUIPMENTS) - sorting function thingy*/
	public static function jtable_sort($sortBy,$pageSize,$startIndex){
	
	$result = DB::select()->from('equipment')->order_by($sortBy['name'],$sortBy['order'])->limit($pageSize)->offset($startIndex)->execute()->as_array();
	
		$sxml = new SimpleXMLElement('<equipmentlist/>');
		$sxml->addAttribute('total', count($result));
			
		foreach($result as $row):
			self::add_equipment_attributes($row, $sxml);
		endforeach;
			
		return self::xaresponse(1, array($sxml));
	}
	
	/*jTable function(USERS) - sorting function thingy*/
	public static function jtable_sort_user($sortBy,$pageSize,$startIndex){
	
	/*to sort the name (first+last) tho it really sorts by first_name*/
	$_var = ($sortBy['name'] == 'name') ? 'first_name' : $sortBy['name'];
	
	$result = DB::select()->from('account')->join('staff','INNER')->on('account.username', '=', 'staff.username')->join('roles', 'INNER')->on('staff.username', '=', 'roles.name')->order_by($_var,$sortBy['order'])->limit($pageSize)->offset($startIndex)->execute()->as_array();
	
			$sxml = new SimpleXMLElement('<entitylist/>');
			$sxml->addAttribute('total', count($result));
			
			foreach($result as $row):
				self::add_user_attributes($row, $sxml);
			endforeach;
		return self::xaresponse(1, array($sxml));   
		
	}

	/*jTable function(EQUIPMENTS) - retrieve last inserted record*/
	public static function last_inserted_equip (){
		$result = DB::select()->from('equipment')->order_by('added','desc')->limit(1)->execute()->as_array();
	$sxml = self::add_equipment_attributes($result[0]);
	return self::xaresponse(1, array($sxml));
	}
	
	/*jTable function(USERS) - retrieve last inserted record*/
	public static function last_inserted_user (){
	$result = DB::select()->from('account')->join('staff','INNER')->on('account.username', '=', 'staff.username')->join('roles', 'INNER')->on('staff.username', '=', 'roles.name')->order_by('account.employee_id','desc')->limit(1)->execute()->as_array();
	$sxml = self::add_user_attributes($result[0]);
	return self::xaresponse(1, array($sxml));
	}

	// Checks if a session is existing
	public static function check_session($session)
	{
		return Model_Sessions::level($session);
	}
		
	/**(Users) Modified for the use of jTable script*/	
	
	// Creates staff record reponse as xml
	private static function create_staff_records($result)
	{
		$sxml = new SimpleXMLElement('<record/>');
		
		$account = $sxml->addChild('account');
		$account->addChild('username',    $result['username']);
		$account->addChild('password',    $result['password']);
		$account->addChild('level',       $result['level']);
		$account->addChild('employee_id', $result['employee_id']);
		
		$info = $sxml->addChild('info');
		$info->addChild('id',             $result['id']);
		$info->addChild('employee_id',    $result['employee_id']);
		$info->addChild('username',       $result['username']);
		$info->addChild('first_name',     $result['first_name']);
		$info->addChild('last_name',      $result['last_name']);
		$info->addChild('gender',         $result['gender']);
		$info->addChild('birthday',       $result['birthday']);
		$info->addChild('country',        $result['country']);
		$info->addChild('city',           $result['city']);
		$info->addChild('street_address', $result['street_address']);
		$info->addChild('mobile',         $result['mobile']);
		$info->addChild('schedule_days',  $result['schedule_days']);
		$info->addChild('schedule_time',  $result['schedule_time']);
		$info->addChild('role_id',        $result['role_id']);
		
		$permissions = $sxml->addChild('permissions', $result['permissions']);
		
		return self::xaresponse(1, array($sxml));
	}
		
	// Fetches equipment info
	public static function fetch_equipment($session, $name)
	{
		Model_Sessions::update($session);

		if (!Model_Sessions::level($session))
		{
			return self::xaresponse(0, array(self::error(2))); 
		}
		
		if (Model_Sessions::level($session) != 1)
		{
			return self::xaresponse(0, array(self::error(3)));
		}
		
		if (!self::check_permission($session, 'view_equipments'))
		{
			return self::xaresponse(0, array(self::error(3)));
		}
	
		$result = DB::select()->from('equipment')
			->where('name', $name)->execute()->as_array();
			
		$successful = (boolean) $result;
		
		return $successful ? self::create_equipment_info($result[0]) : self::xaresponse(1, array(self::error(9)));
	}
		
	// Creates equipment info reponse as xml
	private static function create_equipment_info($result)
	{
		$sxml = new SimpleXMLElement('<equipment/>');
		
		$sxml->addChild('equipment_id', $result['equipment_id']);
		$sxml->addChild('name',         $result['name']);
		$sxml->addChild('description',  $result['description']);
		$sxml->addChild('added',        $result['added']);
		
		return self::xaresponse(1, array($sxml));
	}
			
	// Authenticate login credentials
	public static function login($username, $password)
	{
		if ($username === null or $password === null)
		{
			return self::xaresponse(0, array(self::error(0)));
		}
		
		$result = DB::select('username', 'password', 'level')
			->from('account')
				->where('username', $username)
					->and_where('password', md5($password))
						->execute()->as_array();
		
		if ($result)
		{
			if (Model_Sessions::contains($username))
			{
				return self::xaresponse(0, array(self::error(1)));
			}
			
			$guid = Model_Sessions::generate_guid();
			$level = $result[0]['level'];
			
			$timestamp = Date::time('Asia/Manila')->get_timestamp() + 60 * 30;
			$expiration_date = Date::forge($timestamp, 'Asia/Manila')->format('mysql');
			
			Model_Sessions::save($guid, $username, $level, $expiration_date);
			
			$session  = new SimpleXMLElement('<session>' . $guid . '</session>');
			$username = new SimpleXMLElement('<username>' . $username . '</username>');
			$level    = new SimpleXMLElement('<level>' . $level . '</level>');
			
			return self::xaresponse(1, array($session, $username, $level));
		}
		
		return self::xaresponse(0, array(self::error(0)));
	}
		
	// Logouts a user
	public static function logout($id)
	{
		$successful = (boolean) DB::delete('sessions')->where('id', $id)->execute();
		return $successful ? self::xaresponse(1) : self::xaresponse(0, array(self::error(2)));
	}
		
	// Create a response to a web service
	private static function xaresponse($code, $data = null)
	{
		$sxml = new SimpleXMLElement('<xaresponse></xaresponse>');
			
		$authentication = $sxml->addChild('authentication');
		$authentication->addChild('code', $code);
		
		$text = $code == 1 ? 'OK' : 'INVALID';
		$authentication->addChild('text', $text);
		
		if ($data !== null)
		{
			foreach ($data as $value)
			{
				self::sxml_append($sxml, $value);
			}
		}
		
		return $sxml->asXML();
	}
		
	// Append a simplexmlelement to another simplexmlelement
	private static function sxml_append(SimpleXMLElement $to, SimpleXMLElement $from) 
	{
		$toDom   = dom_import_simplexml($to);
		$fromDom = dom_import_simplexml($from);
		$toDom->appendChild($toDom->ownerDocument->importNode($fromDom, true));
	}
		
	// Creates an error code message
	private static function error($code)
	{
	
		$error_codes = array('Invalid username/password',   // 0
							 'User has an active session.', // 1
							 'Session not existing',        // 2
							 'No permission.',              // 3
							 'Invalid attribute(s)',        // 4
							 'Username not found.',         // 5
							 'Staff id not found.',         // 6
							 'Equipment id not found.',     // 7
							 'Record not found.',			// 8
							 'Equipment not found.');		// 9
		
		$error = new SimpleXMLElement('<error></error>');
		self::sxml_append($error, new SimpleXMLElement('<code>' . $code . '</code>'));
		self::sxml_append($error, new SimpleXMLElement('<description>' . $error_codes[$code] . '</description>'));
		
		return $error;
	}
	
	/**(Users) Modified for the use of jTable script*/		
	// Search for a staff
	public static function search_staff($session, $query = null)
	{
		Model_Sessions::update($session);
	
		if (!Model_Sessions::level($session))
		{
			return self::xaresponse(0, array(self::error(2))); 
		}
		
		if (Model_Sessions::level($session) != 1)
		{
			return self::xaresponse(0, array(self::error(3)));
		}
		
		if (!self::check_permission($session, 'view_records'))
		{
			return self::xaresponse(0, array(self::error(3)));
		}
		
		if($query == "all") {
			$result = DB::select()->from('account')
			->join('staff','INNER')
			->on('account.username', '=', 'staff.username')
			->join('roles', 'INNER')
			->on('staff.username', '=', 'roles.name')
			->execute()->as_array();
		} else {
							
			$result = DB::select()->from('account')
			->join('staff','INNER')
			->on('account.username', '=', 'staff.username')
			->join('roles', 'INNER')
			->on('staff.username', '=', 'roles.name')
			->where('account.username', 'LIKE', '%' . $query . '%')
			->execute()->as_array()	;
								
		}
		
		if(count($result) == 1) 
		{
			$successful = (boolean) $result;
		return $successful ? self::create_staff_records($result[0]) : self::xaresponse(1, array(self::error(8)));
		} 
		else if (count($result) > 1)
		{			
			$sxml = new SimpleXMLElement('<entitylist/>');
			$sxml->addAttribute('total', count($result));
			
			foreach($result as $row):
				self::add_user_attributes($row, $sxml);
			endforeach;
		}else {
			$sxml = new SimpleXMLElement('<error/>');
			$sxml->addChild('code', "1");
			$sxml->addChild('description', "Unable to find the account with the name: " . $query);
		}                                                                                                        
		return self::xaresponse(1, array($sxml));               
	}
		
	/**(Users) Search only ONE single staff (for the nested information of the user in the table)*/	
	public static function search_single_staff($session, $query = null)
	{
		Model_Sessions::update($session);
	
		if (!Model_Sessions::level($session))
		{
			return self::xaresponse(0, array(self::error(2))); 
		}
		
		if (Model_Sessions::level($session) != 1)
		{
			return self::xaresponse(0, array(self::error(3)));
		}
		
		if (!self::check_permission($session, 'view_records'))
		{
			return self::xaresponse(0, array(self::error(3)));
		}
		
		if($query == "all") {
			$result = DB::select()->from('account')
			->join('staff','INNER')
			->on('account.username', '=', 'staff.username')
			->join('roles', 'INNER')
			->on('staff.username', '=', 'roles.name')
			->execute()->as_array();
		} else {
							
			$result = DB::select()->from('account')
			->join('staff','INNER')
			->on('account.username', '=', 'staff.username')
			->join('roles', 'INNER')
			->on('staff.username', '=', 'roles.name')
			->where('account.username', '=',$query )
			->execute()->as_array()	;
								
		}
		
		if(count($result) == 1) 
		{
			$successful = (boolean) $result;
		return $successful ? self::create_staff_records($result[0]) : self::xaresponse(1, array(self::error(8)));
		} 
		else if (count($result) > 1)
		{			
			$sxml = new SimpleXMLElement('<entitylist/>');
			$sxml->addAttribute('total', count($result));
			
			foreach($result as $row):
				self::add_user_attributes($row, $sxml);
			endforeach;
		}else {
			$sxml = new SimpleXMLElement('<error/>');
			$sxml->addChild('code', "1");
			$sxml->addChild('description', "Unable to find the account with the name: " . $query);
		}                                                                                                        
		return self::xaresponse(1, array($sxml));               
	}
	// Adds staff attributes
	private static function add_staff_attributes($row, $entity_list = null)
	{
		if ($entity_list !== null)
		{
			$contact = $entity_list->addChild('contact');
		}
		else
		{
			$contact = new SimpleXMLElement('<contact/>');
		}
		
		$contact->addChild('id', $row['id']);
		$contact->addChild('employee_id', $row['employee_id']);
		$contact->addChild('username', $row['username']);
		$contact->addChild('first_name', $row['first_name']);
		$contact->addChild('last_name', $row['last_name']);
		$contact->addChild('gender', $row['gender']);
		$contact->addChild('birthday', $row['birthday']);
		$contact->addChild('country', $row['country']);
		$contact->addChild('city', $row['city']);
		$contact->addChild('street_address', $row['street_address']);
		$contact->addChild('mobile', $row['mobile']);
		$contact->addChild('schedule_days', $row['schedule_days']);
		$contact->addChild('schedule_time', $row['schedule_time']);
		$contact->addChild('role_id',$row['role_id']);
		
		return $contact;
	}
	
		/*Custom - For jTable (User) plugin*/
	private static function add_user_attributes($row, $entity_list = null)
	{
		if ($entity_list !== null)
		{
			$contact = $entity_list->addChild('contact');
		}
		else
		{
			$contact = new SimpleXMLElement('<contact/>');
		}
		
		$contact->addChild('username', $row['username']);
		$contact->addChild('password', $row['password']);
		$contact->addChild('level', $row['level']);
		$contact->addChild('id', $row['id']);
		$contact->addChild('employee_id', $row['employee_id']);
		$contact->addChild('username', $row['username']);
		$contact->addChild('first_name', $row['first_name']);
		$contact->addChild('last_name', $row['last_name']);
		$contact->addChild('gender', $row['gender']);
		$contact->addChild('birthday', $row['birthday']);
		$contact->addChild('country', $row['country']);
		$contact->addChild('city', $row['city']);
		$contact->addChild('street_address', $row['street_address']);
		$contact->addChild('mobile', $row['mobile']);
		$contact->addChild('schedule_days', $row['schedule_days']);
		$contact->addChild('schedule_time', $row['schedule_time']);
		$contact->addChild('role_id',$row['role_id']);
		$contact->addChild('permissions',$row['permissions']);
		
		return $contact;
	}
		
	// Search for an equipment
	public static function search_equipment($session, $query = null)
	{
		Model_Sessions::update($session);
		
		if (!Model_Sessions::level($session))
		{
			return self::xaresponse(0, array(self::error(2))); 
		}
		
		if (!self::check_permission($session, 'view_equipments'))
		{
			return self::xaresponse(0, array(self::error(3)));
		}
		
		if($query == "all") {
			$result = DB::select()->from('equipment')->execute()->as_array();
		} else {
			$result = DB::select()->from('equipment')
					->where('name', 'LIKE', '%' . $query . '%')
						->execute()
							->as_array();
		}
		
		if(count($result) == 1) 
		{
			$sxml = self::add_equipment_attributes($result[0]);
		} 
		else if (count($result) > 1)
		{			
			$sxml = new SimpleXMLElement('<equipmentlist/>');
			$sxml->addAttribute('total', count($result));
			
			foreach($result as $row):
				self::add_equipment_attributes($row, $sxml);
			endforeach;

		}
		else {
			$sxml = new SimpleXMLElement('<error/>');
			$sxml->addChild('code', "1");
			$sxml->addChild('description', "Unable to find the equipment with the name: " . $query);
		}

		return self::xaresponse(1, array($sxml));
	}
		
	// Adds equipment attributes
	private static function add_equipment_attributes($row, $equipment_list = null)
	{
		if ($equipment_list !== null)
		{
			$equipment = $equipment_list->addChild('equipment');
		}
		else
		{
			$equipment = new SimpleXMLElement('<equipment/>');
		}
		
		$equipment->addChild('id', $row['id']);
		$equipment->addChild('equipment_id', $row['equipment_id']);
		$equipment->addChild('name', $row['name']);
		$equipment->addChild('description', $row['description']);
		$equipment->addChild('added', $row['added']);
		
		return $equipment;
	}
		
	// Search for an account
	public static function search_account($session, $query)
	{
		Model_Sessions::update($session);
	
		if (!Model_Sessions::level($session))
		{
			return self::xaresponse(0, array(self::error(2))); 
		}
		
		if (Model_Sessions::level($session) != 1)
		{
			return self::xaresponse(0, array(self::error(3)));
		}
		
		if (!self::check_permission($session, 'view_records'))
		{
			return self::xaresponse(0, array(self::error(3)));
		}
		
		if($query == "all") {
			$result = DB::select()->from('account')->execute()->as_array();
		} else {
			$result = DB::select()->from('account')
				->where('username', $query)
					->execute()
						->as_array();
		}
		
		if(count($result) == 1) 
		{
			$sxml = self::add_account_attributes($result[0]);
		} 
		else if (count($result) > 1)
		{			
			$sxml = new SimpleXMLElement('<accountlist/>');
			$sxml->addAttribute('total', count($result));
			
			foreach($result as $row):
				self::add_account_attributes($row, $sxml);
			endforeach;
		}
		else {
			$sxml = new SimpleXMLElement('<error/>');
			$sxml->addChild('code', "1");
			$sxml->addChild('description', "Unable to find the account with the name: " . $query);
		}

		return self::xaresponse(1, array($sxml));
	}
		
	// Adds account attributes
	private static function add_account_attributes($row, $account_list = null)
	{
		if ($account_list !== null)
		{
			$account = $account_list->addChild('account');
		}
		else
		{
			$account = new SimpleXMLElement('<account/>');
		}
		
		$account->addChild('username',    $row['username']);
		$account->addChild('password',    $row['password']);
		$account->addChild('level',       $row['level']);
		$account->addChild('employee_id', $row['employee_id']);
		
		return $account;
	}
		
	// Adds a new account
	public static function add_account($session, $data) 
	{
		Model_Sessions::update($session);
		
		if (!Model_Sessions::level($session))
		{
			return self::xaresponse(0, array(self::error(2))); 
		}
		
		if (Model_Sessions::level($session) != 1)
		{
			return self::xaresponse(0, array(self::error(3)));
		}
		
		if (!self::check_permission($session, 'administer_records'))
		{
			return self::xaresponse(0, array(self::error(3)));
		}
		
		if ($data                   === null ||
			$data['permissions']	==  null ||
			$data['username']       ==  null ||
			$data['password']       ==  null ||
			$data['level']          ==  null ||
			$data['first_name']     ==  null ||
			$data['last_name']      ==  null ||
			$data['gender']         ==  null ||
			$data['birthday']       ==  null ||
			$data['country']        ==  null ||
			$data['city']           ==  null ||
			$data['street_address'] ==  null ||
			$data['mobile']         ==  null ||
			$data['schedule_days']  ==  null ||
			$data['schedule_time']  ==  null ||
			$data['role_id']        ==  null)
		{
			return self::xaresponse(1, array(self::error(4)));
		}
		
		$result = DB::select('emp_value')->from('emp_sequence')->execute();
		
		foreach($result[0] as $i){
			$data['employee_id'] = 'EMP-' . $i;
			$result = DB::update('emp_sequence')
				->value("emp_value", $i + 1)
					->where('emp_value', '=', $i)
						->execute();
		}
		
		DB::insert('account')->set(array(
			'username'    => $data['username'],
			'password'    => md5($data['password']),
			'level'       => $data['level'],
			'employee_id' => $data['employee_id'],
		))->execute();
		
		DB::insert('staff')->set(array(
			'employee_id'    => $data['employee_id'],
			'username'       => $data['username'],
			'first_name'     => $data['first_name'],
			'last_name'      => $data['last_name'],
			'gender'         => $data['gender'],
			'birthday'       => $data['birthday'],
			'country'        => $data['country'],
			'city'           => $data['city'],
			'street_address' => $data['street_address'],
			'mobile'         => $data['mobile'],
			'schedule_days'  => $data['schedule_days'],
			'schedule_time'  => $data['schedule_time'],
			'role_id'        => $data['level'],
		))->execute();
		
		$perm = null;
		
		if(isset($data['permissions'][0]))
		{
			$perm .= '{"can_view_records": 1, ';
		}
		else 
		{
			$perm .= '{"can_view_records": 0, ';
		}
			
		if(isset($data['permissions'][1])) {
			$perm .= '"can_view_equipments": 1, ';
		}
		else
		{
			$perm .= '"can_view_equipments": 0, ';
		}
			
		if(isset($data['permissions'][2]))
		{
			$perm .= '"can_administer_records": 1, ';
		}
		else
		{
			$perm .= '"can_administer_records": 0, ';
		}
			
		if(isset($data['permissions'][3]))
		{
			$perm .= '"can_administer_equipments": 1}';
		}
		else
		{
			$perm .= '"can_administer_equipments": 0}';
		}
		
		DB::insert('roles')->set(array(
			'name'        => $data['username'],
			'description' => 'null',
			'permissions' => $perm,
			'level'       => $data['level'],
		))->execute();
		
		return self::xaresponse(1);
	}
		
	// Adds a new equipment
	public static function add_equipment($session, $data) 
	{
		Model_Sessions::update($session);
		
		if (!Model_Sessions::level($session))
		{
			return self::xaresponse(0, self::error(2)); 
		}
		
		if (Model_Sessions::level($session) != 1)
		{
			return self::xaresponse(0, self::error(3));
		}
		
		if (!self::check_permission($session, 'administer_equipments'))
		{
			return self::xaresponse(0, array(self::error(3)));
		}
		
		if ($data                 === null ||
			$data['name']         ==  null ||
			$data['description']  ==  null)
		{
			return self::xaresponse(1, array(self::error(4)));
		}
		
		$result = DB::select()
			->from('equip_sequence')
				->execute()->as_array();
		
		$equip_value = $result[0]['equip_value'];
		
		DB::insert('equipment')->set(array(
			'equipment_id' => 'EQP-' . $equip_value,
			'name'         => $data['name'],
			'description'  => $data['description'],
			'added'        => date('Y-m-d H:i:s'),
		))->execute();
		
		DB::update('equip_sequence')
			->value("equip_value", $equip_value + 1)
				->where('equip_value', $equip_value)
					->execute();
		
		return self::xaresponse(1);
	}
		
	// Deletes an account
	public static function delete_account($session, $username)
	{
		Model_Sessions::update($session);
	
		if (!Model_Sessions::level($session))
		{
			return self::xaresponse(0, array(self::error(2))); 
		}
		
		if (Model_Sessions::level($session) != 1)
		{
			return self::xaresponse(0, array(self::error(3)));
		}
		
		if (!self::check_permission($session, 'administer_records'))
		{
			return self::xaresponse(0, array(self::error(3)));
		}
		
		$successful = (boolean) DB::delete('staff')->where('username', $username)->execute() ;
		
		if($successful){
			DB::delete('account')->where('username', $username)->execute();
			DB::delete('roles')->where('name', $username)->execute();
			return self::xaresponse(1);
		} 
		else 
		{
			return self::xaresponse(1, array(self::error(5)));
		}
	}

	// Deletes an equipment
	public static function delete_equipment($session, $id)
	{
		Model_Sessions::update($session);
	
		if (!Model_Sessions::level($session))
		{
			return self::xaresponse(0, array(self::error(2))); 
		}
		
		if (Model_Sessions::level($session) != 1)
		{
			return self::xaresponse(0, array(self::error(3)));
		}
		
		if (!self::check_permission($session, 'administer_equipments'))
		{
			return self::xaresponse(0, array(self::error(3)));
		}
		
		$successful = (boolean) DB::delete('equipment')->where('id', $id)->execute();
		return $successful ? self::xaresponse(1) : self::xaresponse(1, array(self::error(7)));
	}

	// Updates an account
	public static function update_account($session, $data)
	{
		Model_Sessions::update($session);
	
		if (!Model_Sessions::level($session))
		{
			return self::xaresponse(0, array(self::error(2))); 
		}
		
		if (Model_Sessions::level($session) != 1)
		{
			return self::xaresponse(0, array(self::error(3)));
		}
		
		if (!self::check_permission($session, 'administer_records'))
		{
			return self::xaresponse(0, array(self::error(3)));
		}
		
		if ($data                === null ||
			$data['username']    ==  null ||
			$data['password']    ==  null ||
			$data['level']       ==  null ||
			$data['employee_id'] ==  null)
		{
			return self::xaresponse(1, array(self::error(4)));
		}
		
		$successful = DB::update('account')
			->set(array(
				'username'    => $data['username'],
				'password'    => $data['password'],
				'level'       => $data['level'],
				'employee_id' => $data['employee_id']))
				->where('username', $data['username'])
					->execute();
		
		return $successful ? self::xaresponse(1) : self::xaresponse(1, array(self::error(5)));
	}

	// Updates an equipment
	public static function update_equipment($session, $data)
	{
		Model_Sessions::update($session);
	
		if (!Model_Sessions::level($session))
		{
			return self::xaresponse(0, array(self::error(2))); 
		}
		
		if (Model_Sessions::level($session) != 1)
		{
			return self::xaresponse(0, array(self::error(3)));
		}
		
		if (!self::check_permission($session, 'administer_equipments'))
		{
			return self::xaresponse(0, array(self::error(3)));
		}
		
		if ($data                 === null ||
			$data['id'] ==  null ||
			$data['name']         ==  null ||
			$data['description']  ==  null )
		{
			return self::xaresponse(1, array(self::error(4)));
		}
	
		$successful = DB::update('equipment')
			->set(array(
				'name'         => $data['name'],
				'description'  => $data['description']))
			->where('id', $data['id'])
			->execute();
		
		return $successful ? self::xaresponse(1) : self::xaresponse(1, array(self::error(7)));
	}
		
	// Updates a staff
	public static function update_staff($session, $data)
	{
		Model_Sessions::update($session);
	
		if (!Model_Sessions::level($session))
		{
			return self::xaresponse(0, array(self::error(2))); 
		}
		
		if (Model_Sessions::level($session) != 1)
		{
			return self::xaresponse(0, array(self::error(3)));
		}
		
		if (!self::check_permission($session, 'administer_records'))
		{
			return self::xaresponse(0, array(self::error(3)));
		}
		
		if ($data                   === null ||
			$data['username']  	    ==  null ||
			$data['first_name']     ==  null ||
			$data['last_name']      ==  null ||
			$data['gender']         ==  null ||
			$data['birthday']       ==  null ||
			$data['country']        ==  null ||
			$data['city']           ==  null ||
			$data['street_address'] ==  null ||
			$data['mobile']         ==  null ||
			$data['schedule_days']  ==  null ||
			$data['schedule_time']  ==  null ||
			$data['level'] 		    ==  null ||
			$data['role_id']        ==  null ||
			$data['permissions']    ==  null)
		{
			return self::xaresponse(1, array(self::error(4)));
		}
		
			$successful = DB::update('staff')->set(array(
						'first_name'     => $data['first_name'],
						'username'       => $data['username'],
						'role_id'          => $data['level'],
						'last_name'      => $data['last_name'],
						'gender'         => $data['gender'],
						'birthday'       => $data['birthday'],
						'country'        => $data['country'],
						'city'           => $data['city'],
						'street_address' => $data['street_address'],
						'mobile'         => $data['mobile'],
						'schedule_days'  => $data['schedule_days'],
						'schedule_time'  => $data['schedule_time'],
						'role_id'        => $data['role_id']))
			->where('username', $data['username'])->execute();
							
				DB::update('account')->set(array('level'     => $data['level']))
			->where('username', $data['username'])->execute();					
		$perm = null;

		if(isset($data['permissions']['view_records']))
		{
			$perm .= '{"can_view_records": 1, ';
		}
		else 
		{
			$perm .= '{"can_view_records": 0, ';
		}
			
		if(isset($data['permissions']['view_equipments']))
		{
			$perm .= '"can_view_equipments": 1, ';
		}
		else
		{
			$perm .= '"can_view_equipments": 0, ';
		}
			
		if(isset($data['permissions']['administer_records']))
		{
			$perm .= '"can_administer_records": 1, ';
		}
		else
		{
			$perm .= '"can_administer_records": 0, ';
		}
			
		if(isset($data['permissions']['administer_equipments']))
		{
			$perm .= '"can_administer_equipments": 1}';
		}
		else
		{
			$perm .= '"can_administer_equipments": 0}';
		}

		DB::update('roles')
			->set(array('permissions' => $perm,'level'=> $data['level']))->where('name', $data['username'])->execute();
		
		return $successful ? self::xaresponse(1) : self::xaresponse(1, array(self::error(6)));

	}
		
	// Checks a users permission
	public static function check_permission($session, $permission)
	{
		$username = Model_Sessions::username($session);
	
		$result = DB::select('permissions')->from('roles')
			->where('name', $username)
				->execute()
					->as_array();
		
		$json = json_decode($result[0]['permissions']);

		if ($permission == 'view_records')
		{
			return $json->can_view_records == 1;
		}
		else if ($permission == 'view_equipments')
		{
			return $json->can_view_equipments == 1;
		} 
		else if ($permission == 'administer_records')
		{
			return $json->can_administer_records == 1;
		}
		else if ($permission == 'administer_equipments')
		{
			return $json->can_administer_equipments == 1;
		}
	}
}
?>